package com.naiterui.ehp.bs.cms.modules.sys.aspect;

import cn.hutool.core.util.StrUtil;
import com.naiterui.ehp.bp.security.annotation.SysLog;
import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import com.naiterui.ehp.bp.support.utils.IpUtil;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bs.cms.common.utils.HttpContextUtils;
import com.naiterui.ehp.bs.cms.modules.sys.entity.Log;
import com.naiterui.ehp.bs.cms.modules.sys.service.ILogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 系统日志，切面处理类
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private ILogService logService;

    @Around("@annotation(com.naiterui.ehp.bp.security.annotation.SysLog)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        // 保存日志
        try {
            this.saveSysLog(point, time);
        } catch (Exception e) {
            log.error("获取日志失败", e);
        }

        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Log sysLog = new Log();
        SysLog syslog = method.getAnnotation(SysLog.class);
        // 注解上的描述
        sysLog.setOperation(syslog.value());

        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        sysLog.setMethod(className + "." + signature.getName() + "()");

        // 请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = JsonMapper.toJson(args);
            sysLog.setParams(params);
        } catch (Exception ignored) {

        }

        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        sysLog.setIp(IpUtil.getIp(request));
        try {
            String userName = SecurityUtils.getCurrentUsername();
            // 用户名
            sysLog.setUsername(StrUtil.blankToDefault(userName,"UNKNOWN"));
            sysLog.setCreatedBy(StrUtil.blankToDefault(userName,"UNKNOWN"));
        } catch (Exception e) {
            // 用户名
            sysLog.setUsername("UNKNOWN");
            sysLog.setCreatedBy("UNKNOWN");
        }
        sysLog.setTime(time);
        sysLog.setCreatedAt(new Date());
        // 保存系统日志
        this.logService.saveLog(sysLog);
        log.info("用户: [{}] 请求: [{}] 参数: [{}] 请求耗时: [{}]", sysLog.getCreatedBy(), request.getRequestURI(), sysLog.getParams(), time);
    }
}
